package com.yunxin.core.utils.infra.utils;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.*;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import lombok.extern.slf4j.Slf4j;


/**
 * SCRM加解密/签名工具类
 */
@Slf4j
public class ScrmSignatureUtil {

    /**
     * 基于password生成密钥加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码，用于作为密钥的seed
     * @return AES 加密后的2进制字节码
     */
    public static String encrypt(String content, String password) {
        try {
            // 生成密钥
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());
            keyGen.init(128, secureRandom);
            SecretKey secretKey = keyGen.generateKey();
            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            // 加密
            byte[] encryptByteData = cipher.doFinal(byteContent);

            String result = Base64.getEncoder().encodeToString(encryptByteData);
            // 去掉签名中的换行符
            result = result.replaceAll("\r\n","").replaceAll("\n", "");
            return result;
        } catch (Exception e) {
            log.error("加密失败: " + e);
        }
        return null;
    }

    /**
     * 解密
     * @param contentString   已加密需解密的字符串
     * @param password        解密秘钥
     * @return
     */
    public static String decrypt(String contentString, String password){
        try{
            Base64.Decoder decoder = Base64.getDecoder();
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
            byte[] decryptBytes = cipher.doFinal(decoder.decode(contentString));

            return new String(decryptBytes);
        }catch(Exception e){
            log.error("解密失败: " + e);
        }
        return null;
    }


    /**
     * 将Map转化成String串
     */
    public static String convertMap2String(Map<String, String> paramsMap) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<>(paramsMap.keySet());
        Collections.sort(keys);
        int index = 0;
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = paramsMap.get(key);
            if (!key.isEmpty() && !value.isEmpty()) {
                content.append((index == 0 ? "" : "&") + key + "=" + value);
                index++;
            }
        }
        return content.toString();
    }

    /**
     * 将String转Map
     */
    public static Map<String, String> convertString2Map(String targetString){
        Map<String, String> map = new HashMap<>();
        String[] strings = targetString.split("&");
        for (int i = 0; i < strings.length; i++) {
            String[] keyValue = strings[i].split("=");
            map.put(keyValue[0], keyValue[1]);
        }
        return map;
    }

}
